import { payment } from "../api/Interface/pay";
import { isPro } from "../utils/env";
import errorCode from "../utils/http/errorCode";
import BasicConfig from "../utils/config";
/**
 * 拉卡拉半屏支付
 */
export const useLakalaPay = (resp_data) => {
  console.log("resp_data", resp_data);
  const counterUrl = resp_data.counter_url; // 获取后台返回的counter_url
  const appId = "wx889424d565967811"; // 默认为：拉卡拉聚合收银台小程序的appId
  if (
    counterUrl.includes("q.huijingcai.top") ||
    counterUrl.includes("q.lakala.com")
  ) {
    appId = "wxc3e4d1682da3053c"; // 拉卡拉收款宝小程序appId
  }
  //   console.log(
  //     "useLakalaPay path",
  //     `payment-cashier/pages/checkout/index?source=WECHATMINI&counterUrl=${counterUrl}`
  //   );
  console.log(
    "useLakalaPay path",
    `payment-cashier/pages/checkout/index?source=WECHATMINI&counterUrl=${encodeURIComponent(
      counterUrl
    )}`
  );
  wx.openEmbeddedMiniProgram({
    appId,
    path: `payment-cashier/pages/checkout/index?source=WECHATMINI&counterUrl=${encodeURIComponent(
      counterUrl
    )}`,
    // path: `payment-cashier/pages/checkout/index?source=WECHATMINI&counterUrl=${counterUrl}`,
    // envVersion: isPro ? "release" : "trial",
    envVersion: "release",
    // release: 正式版  trial: 体验版
    success(res) {
      // 打开成功
      console.log("打开半屏支付成功", res);
    },
    fail(err) {
      console.log("打开半屏支付err", err);
    },
  });
};

/**
 * 微信支付
 */
export const useWechatPay = (params) => {
  return new Promise((resolve, reject) => {
    const { localNo, type } = params;
    payment({ localNo, type }).then((res) => {
      if (res.code === errorCode.success) {
        const {
          time_stamp,
          nonce_str,
          package: packageStr,
          sign_type,
          pay_sign,
        } = res.data.resp_data.acc_resp_fields;
        const payParams = {
          timeStamp: time_stamp,
          nonceStr: nonce_str,
          package: packageStr,
          signType: sign_type,
          paySign: pay_sign,
        };
        uni.requestPayment({
          ...payParams,
          success: (result) => {
            if (result.errMsg === "requestPayment:ok") {
              // jumpPage({
              //   to: "/package-service/pages/order/result",
              // });
              resolve({ code: errorCode.success });
            } else {
              // BasicConfig.toast("支付失败,请联系管理员!");
              resolve({ code: errorCode.default });
            }
            resolve(result);
          },
          fail: (error) => {
            reject(error);
          },
        });
      } else {
        BasicConfig.toast(res.msg);
        resolve(res);
      }
    });
  });
  // return new Promise((resolve, reject) => {
  //   uni.requestPayment({
  //     ...params,
  //     success: (result) => {
  //       resolve(result);
  //     },
  //     fail: (error) => {
  //       reject(error);
  //     },
  //   });
  // });
};

/**
 * 支付
 * @param {Ojbect} params 支付参数
 * @param {String} payMode 支付模式 wechat.微信 lakala.拉卡拉 tiktok.抖音支付
 */
export const usePayment = (params, payMode = "wechat") => {
  return new Promise((resolve, reject) => {
    const { localNo, type } = params;
    switch (payMode) {
      case "wechat":
        payment(params)
          .then((res) => {
            if (res.code === errorCode.success) {
              const {
                time_stamp,
                nonce_str,
                package: packageStr,
                sign_type,
                pay_sign,
              } = res.data.resp_data.acc_resp_fields;
              const payParams = {
                timeStamp: time_stamp,
                nonceStr: nonce_str,
                package: packageStr,
                signType: sign_type,
                paySign: pay_sign,
              };
              uni.requestPayment({
                ...payParams,
                success: (result) => {
                  console.log("支付", result);
                  if (result.errMsg === "requestPayment:ok") {
                    resolve({ code: errorCode.success, msg: "支付成功" });
                  } else {
                    resolve({
                      code: errorCode.default,
                      msg: "支付失败，请联系管理员",
                    });
                  }
                  resolve(result);
                },
                fail: (error) => {
                  console.log("支付 fail", error);
                  reject(error);
                },
              });
            } else {
              BasicConfig.toast(res.msg);
              resolve(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
        break;
      case "tiktok":
        uni.requestPayment({
          service:5,
          getOrderStatus:"",
          success: (result) => {
            console.log("支付", result);
            if (result.errMsg === "requestPayment:ok") {
              resolve({ code: errorCode.success, msg: "支付成功" });
            } else {
              resolve({
                code: errorCode.default,
                msg: "支付失败，请联系管理员",
              });
            }
            resolve(result);
          },
          fail: (error) => {
            console.log("支付 fail", error);
            reject(error);
          },
        });
        break;
      default:
        break;
    }
  });
};
